<?php

namespace hiduoke\services\douyinMinApp;

use app\common\model\platform\PlatformApp;
use hiduoke\services\douyinMinApp\API\BaseApi;
use hiduoke\services\douyinMinApp\API\DouyinApi;
use think\facade\Cache;

/**
 * Notes: 抖音自建/服务商平台共用方法类
 * Create by :  刘泓宾<514660094@qq.com>
 * Copyright :  copyright (c) 多客怪兽, www.dkyx.cc
 * Created on:  2024/3/14 15:56
 */
class DouyinMinApp extends BaseApi
{
    /**
     * 抖音服务商对象
     * @var DouyinMinAppServer
     */
    public $DYServer;
    /**
     * 抖音自建配置
     * @var array|mixed|null
     */
    public $config = null;
    /**
     * 抖音小程序类型 0 自建 1服务商
     * @var null
     */
    public $auth_type = null;

    public $appid = '';

    /**
     * 错误说明
     * @var string
     */
    public $err_msg;
    /**
     * 错误码
     * @var int
     */
    public $err_code;

    public function __construct($platform_app_id = 0)
    {
        if (!$platform_app_id) {
            $platform_app_id = get_appid();
        }
        $this->platform_app = (new PlatformApp())->where(['id' => $platform_app_id])->find();
        $auth = $this->getAuthType();
        if ($auth == 1) {
            // 服务商授权
            $this->DYServer = new DouyinMinAppServer($platform_app_id);
            $this->appid = $this->DYServer->authorization_appid;
        } else {
            // 本地部署
            $this->config = $this->platform_app->server_config ?? [];
            $this->Api = new DouyinApi($this->config);
            $this->appid = $this->config['appid'];
        }
    }

    /**
     * 抖音登录
     * @param $code
     * @param $anonymous_code
     * Create by :  刘泓宾<514660094@qq.com>
     * Copyright :  copyright (c) 多客怪兽, www.dkyx.cc
     * Created on:  2024/3/14 15:22
     * @return array|mixed
     */
    public function login($code, $anonymous_code = '')
    {
        if ($this->auth_type == 0) {
            // 本地
            return $this->Api->login($code, $anonymous_code);
        } else {
            // 服务商
            return $this->DYServer->login($code, $anonymous_code);
        }
    }

    /**
     * 获取AccessToken
     * @doc https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/interface-request-credential/non-user-authorization/get-access-token
     * Create by :  刘泓宾<514660094@qq.com>
     * @return false|mixed
     */
    public function getAccessToken()
    {
        if ($this->auth_type == 0) {
            // 自建小程序凭证
            $key = "gs.douyin.app.access_token." . $this->config['appid'];
            if (Cache::get($key)) {
                return Cache::get($key);
            }
            $res = $this->Api->getAccessToken();
            if ($res['err_no'] == 0) {
                $access_token = $res['data']['access_token'];
                Cache::set($key, $access_token, $res['data']['expires_in'] - 500);
                return $access_token;
            } else {
                $this->err_msg = $res['err_tips'];
                $this->err_code = $res['err_no'];
                return false;
            }
        } else {
            // 服务商 小程序调用凭证
            $res = $this->DYServer->get_authorizer_access_token();
            if (!$res) {
                $this->err_msg = $res['err_msg'];
                $this->err_code = $res['err_code'];
                return false;
            }
            return $res;
        }
    }

    public function getAccessTokenV2()
    {
        if ($this->auth_type == 0) {
            // 自建小程序凭证
            $key = "gs.douyin.app.client_token." . $this->config['appid'];
            if (Cache::get($key)) {
                return Cache::get($key);
            }
            $res = $this->Api->getClientToken();
            if ($res['data']['error_code'] == 0) {
                $access_token = $res['data']['access_token'];
                Cache::set($key, $access_token, $res['data']['expires_in'] - 500);
                return $access_token;
            } else {
                $this->err_msg = $res['err_tips'];
                $this->err_code = $res['err_no'];
                return false;
            }
        } else {
            // 服务商 小程序调用凭证
            $res = $this->DYServer->get_authorizer_access_token_V2();
            if (!$res) {
                $this->err_msg = $res['err_msg'];
                $this->err_code = $res['err_code'];
                return false;
            }
            return $res;
        }
    }

    /**
     * 解密手机号
     *
     * @param string $session_key 前端传递的session_key
     * @param string $iv 前端传递的iv
     * @param string $encryptedData 前端传递的encryptedData
     */
    public function decryptPhone($session_key, $iv, $encryptedData)
    {
        if (strlen($session_key) != 24) {
            return false;
        }
        $aesKey = base64_decode($session_key);
        if (strlen($iv) != 24) {
            return false;
        }
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj = json_decode($result);
        if ($dataObj == null) {
            return false;
        }
        if ($dataObj->watermark->appid != $this->appid) {
            return false;
        }
        return json_decode($result, true);
    }

    /**
     * 获取授权类型 0本地部署 1服务商授权
     * Create by :  刘泓宾<514660094@qq.com>
     * @return int|mixed|null
     */
    public function getAuthType()
    {
        if ($this->auth_type != null) {
            return $this->auth_type;
        }
        if ($this->platform_app) {
            $auth_type = $this->platform_app['server_config']['auth_type'] ?? 0;
            $this->auth_type = $auth_type;
            return $auth_type;
        } else {
            return null;
        }
    }
}
